package com.nd.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nd.dao.*;
import com.nd.pojo.bean.*;
import com.nd.pojo.bo.UpdateGoodsBo;
import com.nd.pojo.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional
public class GoodsServiceImpl implements GoodsService{
    ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    KeywordMapper keywordMapper;

    /**
     * 查询商品
     * @param page 页数
     * @param limit 单页条数
     * @param sort 排序字段
     * @param order 排序方式
     * @param goodsSn 商品编号
     * @param name 商品名称
     * @return
     */
    @Override
    public GoodsListVo queryGoodsListVo(Integer page, Integer limit, String sort, String order, String goodsSn, String name) {
        PageHelper.startPage(page,limit);
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setOrderByClause(sort+" "+order);//排序
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
//      //判断模糊查询
        if(!StringUtils.isBlank(goodsSn)) criteria.andGoodsSnLike("%"+goodsSn+"%");
        if(!StringUtils.isBlank(name)) criteria.andNameLike("%"+name+"%");
        criteria.andDeletedEqualTo(false);//逻辑未删除的
        List<Goods> goodsList = goodsMapper.selectByExampleWithBLOBs(goodsExample);
        //获取总数
        PageInfo<Goods> goodsPageInfo = new PageInfo<>();
        long total = goodsPageInfo.getTotal();
        return new GoodsListVo(total,goodsList);
    }

    /**
     * 删除商品
     * @param goods 商品
     * @return 判断值
     */
    @Override
    public int deleteGoods(Goods goods) {
        goods.setDeleted(true);
        return goodsMapper.updateByPrimaryKey(goods);
    }

    @Override
    /**
     * 获取商品详情
     */
    public GoodsDetailVo queryGoodsDetailById(Integer id) {

        Goods goods = goodsMapper.selectByPrimaryKey(id);
//        String galleryStr = goods.getGallery();

//        TypeFactory typeFactory = objectMapper.getTypeFactory();
//        CollectionType type = typeFactory.constructCollectionType(List.class, String.class);
//        List<String> gallery = null;
//        try {
//            gallery = objectMapper.readValue(galleryStr,type);
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
//        GoodsVo goodsVo = new GoodsVo(goods.getId(),goods.getGoodsSn(),
//                goods.getName(),goods.getCategoryId(),goods.getBrandId(),gallery,
//                goods.getKeywords(),goods.getBrief(),goods.getIsOnSale(),goods.getSortOrder(),
//                goods.getPicUrl(),goods.getShareUrl(),goods.getIsNew(),goods.getIsHot(),
//                goods.getUnit(), goods.getCounterPrice(),goods.getRetailPrice(),goods.getAddTime(),
//                goods.getUpdateTime(), goods.getDeleted(),goods.getDetail());

        //商品货品信息
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        //商品规格信息
        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        //商品参数
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);
        //类目id
        Integer pid = categoryMapper.selectPidById(goods.getCategoryId());
        List<Integer> categoryIds = new ArrayList<>();
        categoryIds.add(pid);
        categoryIds.add(goods.getCategoryId());
        return new GoodsDetailVo(categoryIds,goods,goodsAttributes,goodsSpecifications,goodsProducts);
    }

    @Override
    /**
     * 获取所有品牌商
     */
    public CatAndBrandVo queryCatAndBrandVo() {
        //所有的品牌商
        BrandExample brandExample = new BrandExample();
        List<Brand> brands = brandMapper.selectByExample(brandExample);
        ArrayList<BrandGoodsVo> brandList = new ArrayList<>();
        for (Brand brand : brands) {
            brandList.add(new BrandGoodsVo(brand.getName(),brand.getId()));
        }
        //所有的类目级联表，pid=0
        CategoryExample categoryExample = new CategoryExample();
        //查询所有类目
        categoryExample.createCriteria().andPidEqualTo(0);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        ArrayList<CategoryListVo> categoryListVos = new ArrayList<>();
        for (Category category : categories) {
            List<CategoryChildrenVo> categoryChildrenVos = categoryMapper.selectCategoryChildrenVos(category.getId());
            categoryListVos.add(new CategoryListVo(category.getId(),category.getName(),categoryChildrenVos));
        }
        return new CatAndBrandVo(categoryListVos,brandList);
    }

    @Override
    /**
     * 更新商品
     */
    public int updateGoods(UpdateGoodsBo updateGoodsVo) {
        //更新商品信息
        Goods goods = updateGoodsVo.getGoods();
        if(goods.getRetailPrice().doubleValue()<0||goods.getCounterPrice().doubleValue()<0) return 9997;
        if (insertKeyWords(goods)) return 10000;
        if(StringUtils.isEmpty(goods.getGoodsSn())||StringUtils.isEmpty(goods.getName())) return 9998;
        Goods checkGoods = goodsMapper.selectByPrimaryKey(goods.getId());
        //判断修改后的商品名称是否存在,只要修改之后就判断
        if((!checkGoods.getGoodsSn().equals(goods.getGoodsSn())||!checkGoods.getName().equals(goods.getName()))) {
            if (isExistGoods(goods.getGoodsSn(), goods.getName())) return 9999;
        }
        int goodsRow = goodsMapper.updateByPrimaryKeySelective(goods);
        if (goodsRow == 0) return 10000;
        //更新规格信息，同goods，存在就更新，不存在就新增
        List<GoodsSpecification> specifications = updateGoodsVo.getSpecifications();
        for (GoodsSpecification specification : specifications) {
            if(specification.getId() == null||specification.getId() == 0){
                specification.setId(null);
                if (createSpec(goods.getId(), specification)) return 10000;
            }else {
                specification.setUpdateTime(new Date());
                int specRow = goodsSpecificationMapper.updateByPrimaryKeySelective(specification);
                if (specRow == 0) return 10000;
            }
        }
        List<GoodsProduct> products = updateGoodsVo.getProducts();
        for (GoodsProduct product : products) {
            if(product.getPrice().doubleValue()<0||product.getNumber()<0) return 9997;
            if(product.getId() == null||product.getId() == 0){
                product.setId(null);
                if (createProduct(goods.getId(), product)) return 10000;
            }else {
                product.setUpdateTime(new Date());
                int productRow = goodsProductMapper.updateByPrimaryKeySelective(product);
                if (productRow == 0) return 10000;
            }
        }
        List<GoodsAttribute> attributes = updateGoodsVo.getAttributes();
        for (GoodsAttribute attribute : attributes) {
            if(attribute.getId() == null||attribute.getId()==0){
                attribute.setId(null);
                if (createAttribute(goods.getId(), attribute)) return 10000;
            }else {
                attribute.setUpdateTime(new Date());
                int attributeRow = goodsAttributeMapper.updateByPrimaryKeySelective(attribute);
                if (attributeRow == 0) return 10000;
            }
        }
        //更新成功
        return 0;
    }

    //插入关键字
    private boolean insertKeyWords(Goods goods) {
        Date now = new Date();
        String keywords = goods.getKeywords();
        if(!StringUtils.isBlank(keywords)&&!"".equals(keywords)) {
            String[] splits = keywords.split(",");
            for (String split : splits) {
                if(!StringUtils.isBlank(split)) {
                    Keyword keyword = new Keyword();
                    keyword.setKeyword(split);
                    keyword.setIsHot(goods.getIsHot());
                    KeywordExample keywordExample = new KeywordExample();
                    keywordExample.createCriteria().andKeywordEqualTo(split);
                    long count = keywordMapper.countByExample(keywordExample);
                    keyword.setSortOrder((int) (count + 1));
                    keyword.setAddTime(now);
                    keyword.setUpdateTime(now);
                    int i = keywordMapper.insertSelective(keyword);
                    if (i == 0) return true;
                }
            }
        }
        return false;
    }

    /**
     * 新增参数详情
     * @param goodsId
     * @param attribute
     * @return
     */
    private boolean createAttribute(Integer goodsId, GoodsAttribute attribute) {
        attribute.setGoodsId(goodsId);
        attribute.setAddTime(new Date());
        attribute.setUpdateTime(new Date());
        int attributeInsert = goodsAttributeMapper.insertSelective(attribute);
        if(attributeInsert == 0) return true;
        return false;
    }

    /**
     * 新增商品类型
     * @param goodsId
     * @param product
     * @return
     */
    private boolean createProduct(Integer goodsId, GoodsProduct product) {
        product.setAddTime(new Date());
        product.setUpdateTime(new Date());
        product.setGoodsId(goodsId);
        int productInsert = goodsProductMapper.insertSelective(product);
        if(productInsert == 0) return true;
        return false;
    }

    /**
     * 新增规格
     * @param goodsId
     * @param specification
     * @return
     */
    private boolean createSpec(Integer goodsId, GoodsSpecification specification) {
        specification.setGoodsId(goodsId);
        specification.setAddTime(new Date());
        specification.setUpdateTime(new Date());
        int specInsert = goodsSpecificationMapper.insertSelective(specification);
        return specInsert == 0;
    }

    /**
     * 新增商品
     * @param updateGoodsBo 新增商品参数封装类
     * @return 判断值
     */
    @Override
    public int createGoods(UpdateGoodsBo updateGoodsBo) {
        //新增商品
        Goods goods = updateGoodsBo.getGoods();
        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        if (insertKeyWords(goods)) return 10000;
        if(goods.getRetailPrice().doubleValue()<0||goods.getCounterPrice().doubleValue()<0) return 9997;
        if(StringUtils.isEmpty(goods.getGoodsSn())||StringUtils.isEmpty(goods.getName())) return 9998;
        //判断商品编号与名称是否同时相等
        if (isExistGoods(goods.getGoodsSn(),goods.getName())) return 9999;
        int goodsInsert = goodsMapper.insertSelective(goods);
        if(goodsInsert == 0) return 10000;
        //获取最大主键值
        int goodsId = goodsMapper.selectKey();
        //新增规格
        List<GoodsSpecification> specifications = updateGoodsBo.getSpecifications();
        for (GoodsSpecification specification : specifications) {
            if (createSpec(goodsId, specification)) return 10000;
        }
        List<GoodsProduct> products = updateGoodsBo.getProducts();
        for (GoodsProduct product : products) {
            if(product.getPrice().doubleValue()<0) return 9997;
            if(createProduct(goodsId,product)) return 10000;
        }
        List<GoodsAttribute> attributes = updateGoodsBo.getAttributes();
        for (GoodsAttribute attribute : attributes) {
            if(createAttribute(goodsId,attribute)) return 10000;
        }
        return 0;
    }
    //判断商品编号和名称组合是否已存在
    private boolean isExistGoods(String goodsSn,String goodsName) {
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andGoodsSnEqualTo(goodsSn).andNameEqualTo(goodsName).andDeletedEqualTo(false);
        long count = goodsMapper.countByExample(goodsExample);
        return count > 0;
    }

    @Override
    public CommentsListVo queryGoodsCommentsListVo(Integer page, Integer limit, String sort, String order, Integer userId,Integer valueId) {
        PageHelper.startPage(page,limit);
        CommentExample commentExample = new CommentExample();
        commentExample.setOrderByClause(sort+" "+order);
        CommentExample.Criteria criteria = commentExample.createCriteria();
        criteria.andDeletedEqualTo(false);//逻辑未删除的
        if(userId != null) criteria.andUserIdEqualTo(userId);
        if(valueId != null) criteria.andValueIdEqualTo(valueId);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        PageInfo<Comment> commentPageInfo = new PageInfo<>(comments);
        long total = commentPageInfo.getTotal();
        return new CommentsListVo(total,comments);
    }

    @Override
    public int deleteComment(Comment comment) {
        comment.setUpdateTime(new Date());
        comment.setDeleted(true);
        int deleteRow = commentMapper.updateByPrimaryKey(comment);
        if(deleteRow == 0) return 10000;
        return 0;
    }
}
